<template>
  <div class="RenderContainer" id="RenderCon">
    <!-- <el-dialog title="提示" :visible.sync="saveDialogVisible" width="30%" :append-to-body="true">
      <el-input v-model="Tempname"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>-->

    <!-- 左侧字段 -->
    <div class="left-board" v-if="printType == 'printSet'">
      <!-- <el-select v-model="value" placeholder="请选择">
        <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.name">
        </el-option>
      </el-select>-->

      <!-- 模板的属性 -->
      <div class="templateClass">
        <div style="margin:5px 0">
          <div style="display:flex;justify-content:center;align-items:center;font-size: 16px;">模板属性</div>
        </div>
        <el-form :model="printSetFormParam" size="mini" :inline="true" ref="printSetRef">
          <el-form-item
            v-for="(item, index) in printSetFormParam.params"
            :label="item.title"
            :key="item.paramName +'fpkey'"
            :prop="'params.' + index + '.value'"
            :rules="printSetFormParamRules[item.paramName]"
          >
            <el-input
              v-if="item.type == 'text'"
              v-model="item.value"
              type="text"
              :disabled="!item.allow"
              :placeholder="'请输入' + item.title"
            ></el-input>

            <el-input
              v-else-if="item.type == 'int'"
              v-model="item.value"
              type="number"
              :disabled="!item.allow"
            ></el-input>

            <el-select v-else-if="item.type == 'select'" v-model="item.value">
              <el-option
                v-for="item1 in item.selectItems"
                :key="item1.title"
                :label="item1.title"
                :value="item1.value"
              >{{ item1.title }}</el-option>
            </el-select>

            <template v-else-if="item.type == 'radio'">
              <el-checkbox
                v-if="typeof item.value == 'number'"
                v-model="item.value"
                :true-label="1"
                :false-label="0"
              ></el-checkbox>
              <el-checkbox v-else v-model="item.value" true-label="1" false-label="0"></el-checkbox>
            </template>
          </el-form-item>
        </el-form>
      </div>

      <el-scrollbar class="left-scrollbar">
        <div class="components-list">
          <div class="components-title">
            <svg-icon icon-class="component" />输入型组件
          </div>
          <draggable
            class="components-draggable"
            :list="inputComponents"
            :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
            :clone="cloneComponent"
            draggable=".components-item"
            :sort="false"
            @end="onEnd"
          >
            <template v-for="(element, index) in inputComponents">
              <!-- 检验是否存在二维码 -->
              <div
                v-if="(element.tag == 'qrCode' && printSetFormParam.qrCodeParam !== '') || element.tag != 'qrCode'"
                :key="index"
                class="components-item"
                @click="addComponent(element)"
              >
                <div class="components-body">
                  <svg-icon :icon-class="element.tagIcon" />
                  {{ element.label }}
                </div>
              </div>
            </template>
          </draggable>

          <!-- <div class="components-title">
            <svg-icon icon-class="component" />选择型组件
          </div>
          <draggable class="components-draggable" :list="selectComponents"
            :group="{ name: 'componentsGroup', pull: 'clone', put: false }" :clone="cloneComponent"
            draggable=".components-item" :sort="false" @end="onEnd">
            <div v-for="(element, index) in selectComponents" :key="index" class="components-item"
              @click="addComponent(element)">
              <div class="components-body">
                <svg-icon :icon-class="element.tagIcon" />
                {{ element.label }}
              </div>
            </div>
          </draggable>
          <div class="components-title">
            <svg-icon icon-class="component" /> 布局
          </div>
          <draggable class="components-draggable" :list="layoutComponents"
            :group="{ name: 'componentsGroup', pull: 'clone', put: false }" :clone="cloneComponent"
            draggable=".components-item" :sort="false" @end="onEnd">
            <div v-for="(element, index) in layoutComponents" :key="index" class="components-item"
              @click="addComponent(element)">
              <div class="components-body">
                <svg-icon :icon-class="element.tagIcon" />
                {{ element.label }}
              </div>
            </div>
          </draggable>-->
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board" :style="printType == 'printSet' ? 'margin: 0 350px 0 280px;' : ''">
      <div class="action-bar">
        <!-- <el-button icon="el-icon-download" type="text" @click="download">
          导出vue文件
        </el-button>
        <el-button class="copy-btn-main" icon="el-icon-document-copy" type="text" @click="copy">
          复制代码
        </el-button>-->
        <!-- <el-button class="copy-btn-main" icon="el-icon-document-copy" type="text" @click="setValue">
          设置值
        </el-button>-->
        <el-button
          class="copy-btn-main"
          icon="el-icon-document-copy"
          type="text"
          @click="save"
          v-if="printType == 'printSet'"
        >保存</el-button>

        <!-- 选择是否需要页眉页脚 -->
        <el-button
          class="copy-btn-main"
          icon="el-icon-setting"
          type="text"
          @click="openSettingYM()"
          v-if="printType == 'print'"
        >设置</el-button>

        <!-- <el-button
          class="copy-btn-main"
          icon="el-icon-document-copy"
          type="text"
          v-print="print"
          @click="print()"
          v-if="printType == 'print'"
        >打印</el-button>-->
        <!-- @click="watchPrint" -->
        <el-button
          class="copy-btn-main"
          icon="el-icon-document-copy"
          type="text"
          v-print="print"
          v-if="printType == 'print'"
        >打印</el-button>

        <el-button
          class="delete-btn"
          icon="el-icon-delete"
          type="text"
          @click="empty"
          v-if="printType == 'printSet'"
        >清空</el-button>
      </div>
      <!-- el-scrollbar 带滚动条容器  -->
      <!-- 打印区域 -->

      <el-scrollbar class="center-scrollbar" v-if="printDataList.length == 0">
        <el-row id="Mprint" class="center-board-row" :gutter="formConf.gutter">
          <!--  {{ item }}  -->
          <!-- 标题 -->
          <!-- v-for="(item,index) in printItems" :key="index" -->
          <el-form
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'"
            style="font-size: 15px !important;"
          >
            <!--  【套打设置 printType="printSet"】   draggable--可拖拽的容器组件--vuedraggable  -->
            <!-- drawingList -->
            <draggable
              v-if="printType == 'printSet'"
              ref="draggables"
              :class="{ 'drawing-board': true, 'formboder': formConf.formborder }"
              :list="drawingList"
              :animation="340"
              group="componentsGroup"
            >
              <!-- 遍历表单组件 -->
              <draggable-item
                v-for="(element, index) in drawingList"
                :key="element.renderKey"
                :drawing-list="drawingList"
                :element="element"
                :index="index"
                :active-id="activeId"
                :printType="printType"
                :form-conf="formConf"
                @activeItem="activeFormItem"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
                @thClick="thClick"
              />
            </draggable>

            <!-- 【打印 printType="print"】 如果是打印页面就不可以拖拽 -->
            <div
              v-else
              ref="draggables"
              :class="{ 'drawing-board': true, 'formboder': formConf.formborder }"
              :list="drawingList"
              :animation="340"
              group="componentsGroup"
            >
              <draggable-item
                v-for="(element, index) in drawingList"
                :key="element.renderKey"
                :drawing-list="drawingList"
                :element="element"
                :index="index"
                :active-id="activeId"
                :printType="printType"
                :form-conf="formConf"
                @activeItem="activeFormItem"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
                @thClick="thClick"
              />
            </div>
            <!-- <div style="page-break-after:always"></div> -->
            <div v-show="!drawingList.length" class="empty-info">从左侧拖入或点选组件进行表单设计</div>
          </el-form>
        </el-row>
      </el-scrollbar>
      <el-scrollbar class="center-scrollbar" v-if="printDataList.length != 0">
        <el-row id="Mprint" class="center-board-row" :gutter="formConf.gutter">
          <!--  {{ item }}  -->
          <!-- 标题 -->
          <!-- v-for="(item,index) in printItems" :key="index" -->
          <div style="height:100vh" v-for="(item,index) in printDataList" :key="index+'print'">
            <div style="height:97%">
              <el-form
                :size="formConf.size"
                :label-position="formConf.labelPosition"
                :disabled="formConf.disabled"
                :label-width="formConf.labelWidth + 'px'"
                style="font-size: 15px !important;heigth:90%"
              >
                <!--  【套打设置 printType="printSet"】   draggable--可拖拽的容器组件--vuedraggable  -->
                <!-- drawingList -->

                <!-- 【打印 printType="print"】 如果是打印页面就不可以拖拽 -->
                <div
                  ref="draggables"
                  :class="{ 'drawing-board': true, 'formboder': formConf.formborder }"
                  :list="item"
                  :animation="340"
                  group="componentsGroup"
                >
                  <draggable-item
                    v-for="(element, index) in item"
                    :key="element.renderKey"
                    :drawing-list="item"
                    :element="element"
                    :index="index"
                    :active-id="activeId"
                    :printType="printType"
                    :form-conf="formConf"
                    @activeItem="activeFormItem"
                    @copyItem="drawingItemCopy"
                    @deleteItem="drawingItemDelete"
                    @thClick="thClick"
                  />
                </div>
              </el-form>
            </div>
            <div style="text-align:center;height:2%">{{index+1}}/{{printDataList.length}}</div>
          </div>
        </el-row>
      </el-scrollbar>
    </div>

    <right-panel
      :active-data="activeData"
      :form-conf="formConf"
      :show-field="!!drawingList.length"
      @tag-change="tagChange"
      :paramsData="paramsData"
      v-if="printType == 'printSet'"
      class="ringt-board"
    />

    <code-type-dialog
      :visible.sync="dialogVisible"
      title="选择生成类型"
      :show-file-name="showFileName"
      @confirm="generate"
    />
    <input id="copyNode" type="hidden" />

    <!-- 页眉页脚弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="yeMei"
      width="20%"
      :before-close="CloseyeMei"
      :append-to-body="true"
    >
      <span>页眉</span>
      <el-input
        placeholder="请输入内容"
        v-model="yeMeiData"
        clearable
        size="small"
        style="width:80%;margin-left:5%"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="yeMei = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmYeMei()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 可拖拽组件，vuedraggable 内部的标签可以通过
import draggable from "vuedraggable";
import { saveAs } from "file-saver";
import beautifier from "js-beautify";
import ClipboardJS from "clipboard";
import render from "../../utils/generator/render";
import RightPanel from "./RightPanel";
import QRCode from "qrcodejs2";
import {
  inputComponents,
  // selectComponents,
  // layoutComponents,
  formConf
} from "../../utils/generator/config";
import { beautifierConf, titleCase } from "../../utils/index";
import {
  makeUpHtml,
  vueTemplate,
  vueScript,
  cssStyle
} from "../../utils/generator/html";
import { makeUpJs } from "../../utils/generator/js";
import { makeUpCss } from "../../utils/generator/css";
// import drawingDefalut from '../../utils/generator/drawingDefalut'

import CodeTypeDialog from "./CodeTypeDialog";
import DraggableItem from "./DraggableItem";
import Cookies from "js-cookie";
const emptyActiveData = { style: {}, autosize: {} };
let oldActiveId;
let tempActiveData;

export default {
  components: {
    draggable,
    render,
    RightPanel,
    CodeTypeDialog,
    DraggableItem
  },
  props: [
    "printSetFormParam",
    "printSetSubmitUrl",
    "printSetDataKey",
    "dataId",
    "printText",
    "printItems",
    "printType",
    "formConfData",
    "printTeamItems",
    "standardTemplate"
  ],
  data() {
    return {
      print: {
        id: "Mprint",
        popTitle: "&nbsp", // 打印配置页上方标题 不需要页眉的时候加上&nbsp;

        extraCss: "", //为打印区域提供Stylesheet样式表
        targetStyles: ["*"], // 允许打印所有样式属性
        beforeOpenCallback(vue) {
          vue.printLoading = true;
          console.log("打开之前");
        },
        openCallback(vue) {
          vue.printLoading = false;
          console.log("执行了打印");
        },
        closeCallback(vue) {
          vue.watchPrint();
        }
      },
      tableIndex: 0,
      reHeight: 0,

      yeMeiData: "", //页眉数据
      yeMei: false, //页眉弹框控制
      printDataList: [], //打印数据
      printId: "",
      options: [],
      idGlobal: 100,
      formConf,
      inputComponents,
      printlist: "",
      // selectComponents,
      // layoutComponents,
      labelWidth: 100,
      // drawingList: drawingDefalut,   // 标签数据
      drawingList: [], // 标签数据
      drawingData: {},
      activeId: 1,
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: {},
      value: "",
      saveDialogVisible: false,
      Tempname: "",
      printSetFormParamRules: {},
      paramsData: [],
      orgData: null // 当前阻止
    };
  },
  async created() {
    this.orgData = JSON.parse(sessionStorage.getItem("orgData"));

    if (this.printType == "printSet") {
      this.printSetFormParam.params.forEach(item => {
        if (!item.null) {
          this.$set(this.printSetFormParamRules, item.paramName, [
            {
              required: true,
              message: "必填项！",
              trigger: "blur"
            }
          ]);
        } else {
          this.$set(this.printSetFormParamRules, item.paramName, []);
        }
      });
      // 请求填充字段数据
      let { data: res } = await this.$http.get(
        "/api" + this.printSetFormParam.getUrl
      );
      if (res.result) {
        this.paramsData = res.list; // 填充字段
        // console.log(this.paramsData);
      } else {
        this.$message.error(res.result);
      }
    }
    if (
      this.printType == "print" &&
      this.drawingList.length != 0 &&
      this.printTeamItems
    ) {
      for (let index = 0; index < this.printTeamItems.length; index++) {
        const datal = JSON.parse(JSON.stringify(this.printText));
        datal.map((item, inx, arr) => {
          console.log(item.type);

          if (item.type == "tableList" && this.standardTemplate) {
            // prntItems = [{},{},{}]
            let dataList = []; // 符合条件的新数组

            if (this.tableIndex == 0) {
              console.log(this.printTeamItems[index].printMaterial);
              this.printTeamItems[index].processItem.forEach(items => {
                let list = {};
                item.tableHeader.forEach(headItem => {
                  if (!items[headItem.paramName]) {
                    items[headItem.paramName] = "";
                  }
                  for (let key in items) {
                    if (headItem.paramName == key) {
                      this.$set(list, key, items[key]);
                    }
                  }
                });
                dataList.push(list);
              });
              this.tableIndex = 1;
            } else if (
              this.tableIndex > 0 &&
              this.printTeamItems[index].printMaterial
            ) {
              console.log(this.printTeamItems[index].printMaterial);

              this.printTeamItems[index].printMaterial.forEach(items => {
                let list = {};
                item.tableHeader.forEach(headItem => {
                  if (!items[headItem.paramName]) {
                    items[headItem.paramName] = "";
                  }
                  for (let key in items) {
                    if (headItem.paramName == key) {
                      this.$set(list, key, items[key]);
                    }
                  }
                });
                dataList.push(list);
              });
              this.tableIndex = 0;
            } else {
              this.tableIndex = 0;
              console.log(this.printTeamItems[index].printMaterial);
            }
            datal[inx].tableData.splice(0, dataList.length, ...dataList);
          } else if (item.type == "tableList" && !this.standardTemplate) {
            console.log(this.standardTemplate);

            let dataList = []; // 符合条件的新数组
            this.printTeamItems[index].processItem.forEach(items => {
              let list = {};
              item.tableHeader.forEach(headItem => {
                if (!items[headItem.paramName]) {
                  items[headItem.paramName] = "";
                }
                for (let key in items) {
                  if (headItem.paramName == key) {
                    this.$set(list, key, items[key]);
                  }
                }
              });
              dataList.push(list);
            });
            datal[inx].tableData.splice(0, dataList.length, ...dataList);
          } else if (item.type == "textChange") {
            for (let key in this.printTeamItems[index]) {
              if (item.vModel == key) {
                datal[inx].tableData = this.printTeamItems[index][key];
                console.log(datal[inx].tableData);
              }
            }
          } else if (item.vModel) {
            for (let key in this.printTeamItems[index]) {
              if (item.vModel == key) {
                datal[inx].defaultValue = this.printTeamItems[index][key];
              }
            }
          }
        });
        this.printDataList[index] = datal;
      }
    }
  },
  computed: {},

  watch: {
    // 监听表单字段标题的改变，修改提示值
    // 'activeData.label': function (val, oldVal) {
    //   if (
    //     this.activeData.placeholder === undefined
    //     || !this.activeData.tag
    //     || oldActiveId !== this.activeId
    //   ) {
    //     return
    //   }
    //   this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val;
    // },
    // 监听表单字段名的改变，修改提示值
    // 'activeData.vModel': {
    //   handler(val) {
    //     this.activeData.placeholder = "请输入" + this.activeData.label;

    //   }
    // },

    formConf: {
      immediate: true,
      deep: true,
      handler(val) {
        this.formConf = val;
        //console.log(this.formConf);
      }
    },
    formConfData: {
      immediate: true,
      deep: true,
      handler(val) {
        this.formConf = val;
        // console.log(val);
      }
    },
    activeId: {
      handler(val) {
        oldActiveId = val;
      },
      immediate: true
    },
    value: {
      handler(val) {
        //  this.drawingList = [];
        let model = this.options.find(x => x.name == val);
        // console.log(model);
        if (model != undefined) {
          //this.$set(this,this.drawingList,model.items)
          this.drawingList = JSON.parse(JSON.stringify(model.items));
          console.log(this.drawingList);

          this.activeId = model.items[0].formId;
          this.activeData = model.items[0];
        }
      },
      immediate: true
    },
    printText: {
      handler(val) {
        let tableData = JSON.parse(JSON.stringify(val));
        this.drawingList = tableData;
        let rows = 0;
        let rowIndex = 0;
        let a = 0;
        console.log(tableData);

        tableData.forEach((item, index) => {
          if (item.type == "textChange") {
            rowIndex++;
            if (item.defaultValue) {
              let tableArr = JSON.parse(item.defaultValue).soure;
              let columnsArr = item.columns;

              tableArr.forEach((item1, inx) => {
                item.columns[inx].tableData = item1.tableData;
                if (item1.tableData.length > a) {
                  a = item1.tableData.length;
                }

                if (
                  item.columns.length > tableArr.length &&
                  inx == tableArr.length - 1
                ) {
                  let arr = [];
                  for (let b = 0; b < a; b++) {
                    arr.push("");
                  }
                  for (let i = inx + 1; i < item.columns.length; i++) {
                    item.columns[i].tableData = arr;
                  }
                }
              });
            }

            // let drawColumsData = this.drawingList[index].columns;
            // this.drawingList[index].columns.forEach((item,index) => {
            //   item.tableData = index
            // })

            // this.drawingList[index].rows = this.drawingList[
            //   index
            // ].tableData.length;
            // rows = rows + this.drawingList[index].tableData.length;
            // rowIndex++;
          } else if (item.layout == "textFormRectangle") {
            let t = 0;
            this.reHeight = 0;
            let ix = 0;
            tableData.forEach((it, inx) => {
              if (it.type == "textChange") {
                ix++;
                if (it.defaultValue) {
                  let tableArr = JSON.parse(it.defaultValue).soure;
                  tableArr.forEach((it1, inx) => {
                    if (it1.tableData.length > t) {
                      t = it1.tableData.length;
                    }
                    this.reHeight = this.reHeight + t;
                  });
                }
              }
            });
            item.rows = item.rows + this.reHeight - ix;
          }
        });
        // tableData.forEach((item, index) => {
        //   if (item.layout == "textFormRectangle") {
        //     this.drawingList[index].rows =
        //       this.drawingList[index].rows + rows - rowIndex;
        //   }
        // });
        //console.log(tableData);

        console.log(this.drawingList); //printText
        console.log(this.printItems);
        console.log(this.printTeamItems);

        //填充表格数据
        //this.drawingList 打印模板的总数据
        if (
          this.printType == "print" &&
          this.drawingList.length != 0 &&
          this.printItems.length != 0
        ) {
          this.drawingList.forEach(arr => {
            if (arr.type == "tableList") {
              console.log(this.reHeight);
              console.log(arr.rowCount);
              arr.rowCount = arr.rowCount + this.reHeight - 2;
              console.log(arr.rowCount);
              console.log(arr.tableData);
              let tableTr = {};
              arr.tableHeader.forEach(item => {
                this.$set(tableTr, item.paramName, "");
              });
              if (arr.tableData.length < arr.rowCount) {
                for (var i = arr.tableData.length; i < arr.rowCount; i++) {
                  arr.tableData.push(tableTr);
                }
              }
              console.log(arr.tableData);
              // prntItems = [{},{},{}]
              let dataList = []; // 符合条件的新数组
              this.printItems.forEach(items => {
                // items = {key1:"",key2:""}  每行
                let list = {};

                arr.tableHeader.forEach(headItem => {
                  if (!items[headItem.paramName]) {
                    items[headItem.paramName] = "";
                  }
                  // headItem = {}
                  for (let key in items) {
                    if (headItem.paramName == key) {
                      // list[key] = items[key]
                      this.$set(list, key, items[key]);
                      //console.log(list, key, items[key]);
                    }
                  }
                });
                dataList.push(list);
              });
              arr.tableData.splice(0, dataList.length, ...dataList);
              //
              //   arr.tableData = [];
              //   // 遍历行明细
              //   this.printItems.forEach(items => {
              //     let list = {};
              //     arr.tableHeader.forEach(headItem => {
              //       for (let key in items) {
              //         if (headItem.paramName == key) {
              //           // list[key] = items[key]
              //           this.$set(list, key, items[key]);
              //         }
              //       }
              //     });
              //     arr.tableData.push(list);
              //   });
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    let renderformstr = Cookies.get("renderform");
    // console.log(renderformstr);
    if (renderformstr == undefined || renderformstr == null) {
      this.options = [];
    } else {
      this.options = JSON.parse(renderformstr);
    }
    // console.log(this.options);
    const clipboard = new ClipboardJS("#copyNode", {
      text: trigger => {
        const codeStr = this.generateCode();
        this.$notify({
          title: "成功",
          message: "代码已复制到剪切板，可粘贴。",
          type: "success"
        });
        return codeStr;
      }
    });
    clipboard.on("error", e => {
      this.$message.error("代码复制失败");
    });
  },
  methods: {
    activeFormItem(element) {
      this.activeData = element;
      this.activeId = element.formId;
      // console.log(element);
    },
    onEnd(obj, a) {
      if (obj.from !== obj.to) {
        this.activeData = tempActiveData;
        this.activeId = this.idGlobal;
      }
    },
    // 标签的拖拉新增
    addComponent(item) {
      const clone = this.cloneComponent(item);
      this.drawingList.push(clone);
      this.activeFormItem(clone);
    },
    cloneComponent(origin) {
      // console.log(origin);
      const clone = JSON.parse(JSON.stringify(origin));
      clone.formId = ++this.idGlobal;
      if (clone.layout != "tableFormItem") {
        clone.span = formConf.span;
      }
      clone.renderKey = +new Date(); // 改变renderKey后可以实现强制更新组件
      if (!clone.layout) clone.layout = "colFormItem";
      if (clone.layout === "colFormItem") {
        // clone.vModel = `field${this.idGlobal}`
        // clone.placeholder !== undefined && (clone.placeholder += clone.label)
        tempActiveData = clone;
      } else if (clone.layout === "rowFormItem") {
        delete clone.label;
        clone.componentName = `row${this.idGlobal}`;
        clone.gutter = this.formConf.gutter;
        tempActiveData = clone;
      } else if (
        clone.layout === "textFormItem" ||
        clone.layout === "textInputFormItem" ||
        clone.layout == "tableFormItem" ||
        clone.layout == "textFormRectangle" ||
        clone.layout == "textFormChange"
      ) {
        tempActiveData = clone;
      } else if (clone.layout == "qrCodeFormItem") {
        clone.defaultValue = `{{${this.printSetFormParam.qrCodeParam}}}`;
        tempActiveData = clone;
      } else if (clone.layout == "pictureFormItem") {
        clone.defaultValue = `{{${this.printSetFormParam.qrCodeParam}}}`;
        tempActiveData = clone;
      }
      return tempActiveData;
    },
    AssembleFormData() {
      this.formData = {
        fields: JSON.parse(JSON.stringify(this.drawingList)),
        ...this.formConf
      };
    },
    generate(data) {
      const func = this[`exec${titleCase(this.operationType)}`];
      this.generateConf = data;
      func && func(data);
    },
    execRun(data) {
      this.AssembleFormData();
      this.drawerVisible = true;
    },
    execDownload(data) {
      const codeStr = this.generateCode();
      const blob = new Blob([codeStr], { type: "text/plain;charset=utf-8" });
      saveAs(blob, data.fileName);
    },
    execCopy(data) {
      document.getElementById("copyNode").click();
    },
    // 清空事件
    empty() {
      this.$confirm("确定要清空所有组件吗？", "提示", { type: "warning" }).then(
        () => {
          this.drawingList = [];
        }
      );
    },
    // 标签的直接复制
    drawingItemCopy(item, parent) {
      let clone = JSON.parse(JSON.stringify(item));
      clone = this.createIdAndKey(clone);
      parent.push(clone);
      this.activeFormItem(clone);
    },
    createIdAndKey(item) {
      item.formId = ++this.idGlobal;
      item.renderKey = +new Date();
      if (item.layout === "colFormItem") {
        item.vModel = `field${this.idGlobal}`;
      } else if (item.layout === "rowFormItem") {
        item.componentName = `row${this.idGlobal}`;
      }
      if (Array.isArray(item.children)) {
        item.children = item.children.map(childItem =>
          this.createIdAndKey(childItem)
        );
      }
      return item;
    },
    drawingItemDelete(index, parent) {
      parent.splice(index, 1);
      this.$nextTick(() => {
        const len = this.drawingList.length;
        if (len) {
          this.activeFormItem(this.drawingList[len - 1]);
        }
      });
    },
    generateCode() {
      const { type } = this.generateConf;
      this.AssembleFormData();
      const script = vueScript(makeUpJs(this.formData, type));
      const html = vueTemplate(makeUpHtml(this.formData, type));
      const css = cssStyle(makeUpCss(this.formData));
      return beautifier.html(html + script + css, beautifierConf.html);
    },
    download() {
      this.dialogVisible = true;
      this.showFileName = true;
      this.operationType = "download";
    },
    run() {
      this.dialogVisible = true;
      this.showFileName = false;
      this.operationType = "run";
    },
    copy() {
      this.dialogVisible = true;
      this.showFileName = false;
      this.operationType = "copy";
    },
    // 组件的类型
    tagChange(newTag) {
      newTag = this.cloneComponent(newTag);
      newTag.vModel = this.activeData.vModel;
      newTag.formId = this.activeId;
      newTag.span = this.activeData.span;
      delete this.activeData.tag;
      delete this.activeData.tagIcon;
      delete this.activeData.document;
      Object.keys(newTag).forEach(key => {
        if (
          this.activeData[key] !== undefined &&
          typeof this.activeData[key] === typeof newTag[key]
        ) {
          newTag[key] = this.activeData[key];
        }
      });
      this.activeData = newTag;
      this.updateDrawingList(newTag, this.drawingList);
    },
    updateDrawingList(newTag, list) {
      const index = list.findIndex(item => item.formId === this.activeId);
      if (index > -1) {
        list.splice(index, 1, newTag);
      } else {
        list.forEach(item => {
          if (Array.isArray(item.children))
            this.updateDrawingList(newTag, item.children);
        });
      }
    },
    // print() {
    //   let draggables = this.$refs["draggables"];
    //   draggables.$children.forEach(element => {
    //     // console.log(element)
    //     element.$el.classList.remove("active-from-item");
    //   });
    // },
    //这里是写死的,请自行实际接口替换
    setValue() {
      console.log(this.drawingList);
      let mode = [
        { name: "k", value: "12" },
        { name: "mobile", value: "19216811111" },
        { name: "c", value: "测试写入数据" }
      ];
      this.drawingList.forEach(e => {
        let data = mode.find(x => x.name == e.vModel);
        if (data != undefined) {
          this.$set(e, "defaultValue", data.value);
          // e.defaultValue = data.value;
        }
      });
    },
    //保存demo 暂存到cookies里面,实际对接后端接口
    save() {
      this.$refs.printSetRef.validate(async valid => {
        if (!valid) {
          this.$message.error("请填写左侧模板属性");
        } else {
          let formParam = {};
          this.printSetFormParam.params.forEach(item => {
            if (item.type == "select") {
              formParam[item.actionValue] = parseInt(item.value);
            } else if (item.type == "radio") {
              formParam[item.paramName] = parseInt(item.value);
            } else {
              formParam[item.paramName] = item.value;
            }
          });

          let { data: res } = await this.$http.post(
            "/api" + this.printSetSubmitUrl,
            {
              id: this.dataId,
              orgId: this.orgData.orgType,
              dataParam: JSON.stringify(formParam),
              printTemplate: JSON.stringify(this.drawingList),
              fromTemplate: JSON.stringify(this.formConf)
            }
          );
          if (res.result) {
            // console.log(res);
            this.$message.success(res.msg);
            this.$emit("printSetReturn");
          } else {
            this.$message.warning(res.msg);
          }
        }
      });
    },
    // 监听表格头部的事件
    thClick(item) {
      //console.log(item);
    },
    openSettingYM() {
      this.yeMei = true;
    },
    CloseyeMei() {
      this.yeMei = false;
    },
    confirmYeMei() {
      this.print.popTitle = this.yeMeiData;
      this.yeMei = false;
    },
    async watchPrint() {
      let ids = [];
      console.log(this.printTeamItems);
      this.printTeamItems.forEach((item, index) => {
        ids[index] = item.id;
      });

      let { data: res } = await this.$http.get(
        "/api/countProcessWorkOrderPrintNum?ids=" + ids
      );
      if (res.result) {
        console.log(res);
      } else {
        this.$message.error(res.result);
      }
    }
  }
};
</script>

<style lang='scss'>
@media print {
  .el-input__inner {
    color: red !important;
  }
}
.RenderContainer #Mprint .el-table__cell div {
  margin: 0 auto;
}

.RenderContainer {
  .center-board {
    .center-scrollbar {
      .el-input--mini {
        .el-input__inner {
          //height: 40px !important;
          color: black;
          font-weight: 600;
          font-size: 18px;
        }
      }
    }
    .el-input--medium .el-input__inner {
      text-align: center;
      color: black;
      font-weight: 400;
      font-size: 18px;
    }
    .textDivClass {
      img {
        height: 100%;
        width: 100%;
      }
    }
  }
}

#print .formboder .el-form-item__label:after {
  content: "";
  border-right: 1px solid #121315;
  // border-right: 1px solid #1a5de4;
  margin-left: 5px;
  height: 100%;
  margin-top: -4px;
  position: absolute;
}

#print .form-no-boder .el-form-item__label:after {
  content: "";
  // border-right: 1px solid #000;
  border-right: none;
  margin-left: 5px;
  height: 100%;
  margin-top: -4px;
  position: absolute;
}

input,
textarea {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial,
    sans-serif, Apple Color Emoji, Segoe UI Emoji;
}

.editor-tabs {
  background: #121315;

  .el-tabs__header {
    margin: 0;
    border-bottom-color: #121315;

    .el-tabs__nav {
      border-color: #121315;
    }
  }

  .el-tabs__item {
    height: 30px;
    line-height: 30px;
    color: #555;
    border-left: 1px solid #121315 !important;
    background: #EEE;
    margin-right: 5px;
    user-select: none;
  }

  .el-tabs__item.is-active {
    background: #1e1e1e;
    border-bottom-color: #1e1e1e !important;
    color: #fff;
  }

  .el-icon-edit {
    color: #f1fa8c;
  }

  .el-icon-document {
    color: #a95812;
  }
}

// home
.right-scrollbar {
  .el-scrollbar__view {
    padding: 12px 18px 15px 15px;
  }
}

.left-scrollbar .el-scrollbar__wrap {
  box-sizing: border-box;
  overflow-x: hidden !important;
  margin-bottom: 0 !important;
}

.center-tabs {
  .el-tabs__header {
    margin-bottom: 0 !important;
  }

  .el-tabs__item {
    width: 50%;
    text-align: center;
  }

  .el-tabs__nav {
    width: 100%;
  }
}

.reg-item {
  padding: 12px 6px;
  background: #f8f8f8;
  position: relative;
  border-radius: 4px;

  .close-btn {
    position: absolute;
    right: -6px;
    top: -6px;
    display: block;
    width: 16px;
    height: 16px;
    line-height: 16px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 50%;
    color: #fff;
    text-align: center;
    z-index: 1;
    cursor: pointer;
    font-size: 12px;

    &:hover {
      background: rgba(210, 23, 23, 0.5);
    }
  }

  & + .reg-item {
    margin-top: 18px;
  }
}

.action-bar {
  & .el-button + .el-button {
    margin-left: 15px;
  }

  & i {
    font-size: 20px;
    vertical-align: middle;
    position: relative;
    top: -1px;
  }
}

.custom-tree-node {
  width: 100%;
  font-size: 14px;

  .node-operation {
    float: right;
  }

  i[class*="el-icon"] + i[class*="el-icon"] {
    margin-left: 6px;
  }

  .el-icon-plus {
    color: #409eff;
  }

  .el-icon-delete {
    color: #157a0c;
  }
}

.left-scrollbar .el-scrollbar__view {
  overflow-x: hidden;
}

.el-rate {
  display: inline-block;
  vertical-align: text-top;
}

.el-upload__tip {
  line-height: 1.2;
}

$selectedColor: #f6f7ff;
$lighterBlue: #5c87b3;

.components-list {
  padding: 8px;
  box-sizing: border-box;
  height: 100%;

  .components-item {
    display: inline-block;
    width: 48%;
    margin: 1%;
    transition: transform 0ms !important;
  }
}

.components-draggable {
  padding-bottom: 20px;
}

.components-title {
  font-size: 14px;
  color: #222;
  margin: 6px 2px;

  .svg-icon {
    color: #666;
    font-size: 18px;
  }
}

.components-body {
  padding: 8px 10px;
  background: $selectedColor;
  font-size: 12px;
  cursor: move;
  border: 1px dashed $selectedColor;
  border-radius: 3px;

  .svg-icon {
    color: #777;
    font-size: 15px;
  }

  &:hover {
    border: 1px dashed #787be8;
    color: #787be8;

    .svg-icon {
      color: #787be8;
    }
  }
}

.left-board {
  width: 280px;
  position: absolute;
  left: 0;
  top: 50px;
  height: 100vh;
}
.ringt-board {
  margin-top: 50px;
}
.left-scrollbar {
  // height: calc(100vh - 42px);
  overflow: hidden;
}

// 中间打印区域
.center-scrollbar {
  height: calc(100vh - 42px);
  overflow: hidden;
  border-left: 1px solid #f1e8e8;
  border-right: 1px solid #f1e8e8;
  box-sizing: border-box;
}

.center-board {
  height: 100vh;
  width: auto;
  // margin: 0 350px 0 280px;
  box-sizing: border-box;
}

.empty-info {
  position: absolute;
  top: 46%;
  left: 0;
  right: 0;
  text-align: center;
  font-size: 18px;
  color: #ccb1ea;
  letter-spacing: 4px;
}

.action-bar {
  position: relative;
  height: 42px;
  text-align: right;
  padding: 0 15px;
  box-sizing: border-box;
  border: 1px solid #f1e8e8;
  border-top: none;
  border-left: none;

  .delete-btn {
    color: #f56c6c;
  }
}

.logo-wrapper {
  position: relative;
  height: 42px;
  background: #fff;
  border-bottom: 1px solid #f1e8e8;
  box-sizing: border-box;
}

.logo {
  position: absolute;
  left: 12px;
  top: 6px;
  line-height: 30px;
  color: #00afff;
  font-weight: 600;
  font-size: 17px;
  white-space: nowrap;

  > img {
    width: 30px;
    height: 30px;
    vertical-align: top;
  }

  .github {
    display: inline-block;
    vertical-align: sub;
    margin-left: 15px;

    > img {
      height: 22px;
    }
  }
}

.center-board-row {
  // padding: 12px 12px 15px 12px;
  padding: 0 12px 0 0;
  box-sizing: border-box;

  & > .el-form {
    // 69 = 12+15+42
    height: calc(100vh - 69px);
  }
}

.center-board-row .el-form .el-form-item {
  border: 1px solid #000;
}

.drawing-board {
  height: 100%;
  position: relative;

  .components-body {
    padding: 0;
    margin: 0;
    font-size: 0;
  }

  .sortable-ghost {
    position: relative;
    display: block;
    overflow: hidden;

    &::before {
      content: " ";
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      height: 3px;
      background: rgb(89, 89, 223);
      z-index: 2;
    }
  }

  .components-item.sortable-ghost {
    width: 100%;
    height: 60px;
    background-color: $selectedColor;
  }

  .active-from-item {
    & > .el-form-item {
      // background: $selectedColor;
      // border-radius: 6px;
    }

    & > .drawing-item-copy,
    & > .drawing-item-delete {
      display: initial;
    }

    & > .component-name {
      color: $lighterBlue;
    }
  }

  .el-form-item {
    margin-bottom: 15px;
  }
}

.drawing-item {
  position: relative;
  cursor: move;

  &.unfocus-bordered:not(.activeFromItem) > div:first-child {
    border: 1px dashed #ccc;
  }

  .el-form-item {
    padding: 12px 10px;
  }
}

.drawing-row-item {
  position: relative;
  cursor: move;
  box-sizing: border-box;
  border: 1px dashed #ccc;
  // border-radius: 3px;
  padding: 0px;
  //margin-bottom: 15px;

  .drawing-row-item {
    margin-bottom: 2px;
  }

  .el-col {
    margin-top: 22px;
  }

  .el-form-item {
    // margin-bottom: 0;
  }

  .colFormClass .el-form-item__label {
  }

  .drag-wrapper {
    min-height: 80px;
  }

  &.active-from-item {
    border: 1px dashed $lighterBlue;
    box-sizing: border-box;
  }

  .component-name {
    position: absolute;
    top: 0;
    left: 0;
    font-size: 12px;
    color: #bbb;
    display: inline-block;
    padding: 0 6px;
  }
}

.drawing-item,
.drawing-row-item {
  &:hover {
    & > .el-form-item {
      background: $selectedColor;
      // border-radius: 6px;
    }

    & > .drawing-item-copy,
    & > .drawing-item-delete {
      display: initial;
    }
  }

  & > .drawing-item-copy,
  & > .drawing-item-delete {
    display: none;
    position: absolute;
    top: -10px;
    width: 22px;
    height: 22px;
    line-height: 22px;
    text-align: center;
    border-radius: 50%;
    font-size: 12px;
    border: 1px solid;
    cursor: pointer;
    z-index: 1;
  }

  & > .drawing-item-copy {
    right: 56px;
    border-color: $lighterBlue;
    color: $lighterBlue;
    background: #fff;

    &:hover {
      background: $lighterBlue;
      color: #fff;
    }
  }

  & > .drawing-item-delete {
    right: 24px;
    border-color: #f56c6c;
    color: #f56c6c;
    background: #fff;

    &:hover {
      background: #f56c6c;
      color: #fff;
    }
  }
}

.drawing-item .el-form-item {
  overflow: hidden;
  // white-space: nowrap !important;
}

.drawing-item .el-form-item {
  padding: 4px 4px !important;
}

.formboder .el-form-item {
  border: 0.1rem solid #6a6969;
  margin: 0 -1px -1px 0;
}

.form-no-boder .el-form-item {
  border: 0rem !important;
  margin: 0 1px 1px 0;
}

.drawing-item .el-form-item__label {
  font-size: inherit !important;
  color: #000;
}

#print .el-input__inner {
  border-radius: 0 !important;
  border: 0px solid #dcdfe6 !important;
  color: #000;
  // border-bottom: 1px solid !important;
}

.hiddenValue .el-input__inner {
  display: none;
}

.hiddenValue .el-textarea__inner {
  display: none;
}

#print .el-textarea__inner {
  background-color: transparent !important;
  border-radius: 0 !important;
  border: 0px solid #dcdfe6 !important;
  // border-bottom: 1px solid !important;
  // resize: none;
}

.drawing-row-item .drag-wrapper {
  min-height: 38px !important;
}

.templateClass .el-form-item__label {
  font-size: 12px !important;
}

.templateClass {
  border-bottom: 1px solid #000;
}

// div 标签
.formboder .textDivClass {
  border: 1px solid #000;
  margin: 0 -1px -1px 0;
}

// div border标签
.formborderTop {
  .textDivClass {
    border: 0rem;
    border-top: 1px solid #000 !important;
    margin: 0 -1px -1px 0;
  }
}
.formborderRight {
  .textDivClass {
    border: 0rem;
    border-right: 1px solid #000 !important;
    margin: 0 -1px 1px 0 !important;
  }
}
.formborderBottom {
  .textDivClass {
    border: 0rem;
    border-bottom: 1px solid #000 !important;
    margin: 0 -1px -1px 0;
  }
}
.formborderLeft {
  .textDivClass {
    border: 0rem;
    border-left: 1px solid #000 !important;
    margin: 0 -1px -1px 0;
  }
}

.form-no-boder .textDivClass {
  border: 0rem;
  margin: 0 1px 1px 0;
}

.tableFormItemClass {
  display: flex;
  align-content: center;
  justify-items: center;
}
</style>
<style>
/* body,
html {
  margin: 0;
  padding: 0;
  font-size: 10px;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
} */
</style>
